from typing import List, Iterator

from chernc.treediff.gumtree.actions.model.action import Action

class EditScript:
    def __init__(self):
        self.actions: List[Action] = []

    def __iter__(self) -> Iterator[Action]:
        return iter(self.actions)

    def add(self, action: Action):
        """Add an action to the script."""
        self.actions.append(action)

    def add_at(self, index: int, action: Action):
        """Add an action at the specified index."""
        self.actions.insert(index, action)

    def get(self, index: int) -> Action:
        """Return the action at the given index."""
        return self.actions[index]

    def size(self) -> int:
        """Return the number of actions."""
        return len(self.actions)

    def remove(self, action: Action) -> bool:
        """Remove the provided action from the script."""
        try:
            self.actions.remove(action)
            return True
        except ValueError:
            return False

    def remove_at(self, index: int) -> Action:
        """Remove the action at the specified index."""
        return self.actions.pop(index)

    def as_list(self) -> List[Action]:
        """Return the edit script as a list of actions."""
        return self.actions

    def last_index_of(self, action: Action) -> int:
        """Return the index of the last occurrence of the action in the script."""
        try:
            return len(self.actions) - 1 - self.actions[::-1].index(action)
        except ValueError:
            return -1
